<template>
  <a-modal :open="open" width="950px" title="手术预约" ok-text="保存" :ok-button-props="{ disabled: !isCompleted }" centered @ok="onOk" @cancel="onCancel">
    <div class="flex">
      <div class="w-1/2 pr-2">
        <SelectTable
          v-model:value="formState.brName"
          type="患者"
          placeholder="姓名/助记码/卡号/手机号/证件号码"
          :disabled="rowData.aptmLsh"
          :maxlength="20"
          empty-close
          @select="onSelectPatient"
        />
        <UserCard :user-data="userInfo" class="mt-3">
          <div class="flex flex-col justify-between px-5">
            <div class="flex justify-between items-center mt-2">
              <LabelValue label-align="right" :label-width="140" label="负责人" :value="userInfo.brFzrName" />
              <LabelValue label-align="right" label="咨询师" :value="userInfo.brZxsName" />
            </div>
            <a-descriptions class="mt-3" :column="1">
              <a-descriptions-item label="关注项目" class="w-full pb-5">
                <a-select
                  v-model:value="userInfo.brZlxm"
                  class="w-full"
                  placeholder="请选择"
                  :options="interestProject"
                  allow-clear
                  mode="multiple"
                  max-tag-count="responsive"
                  @change="onChangeSelect"
                />
              </a-descriptions-item>
              <a-descriptions-item label="客户来源" class="w-full">
                <SelectCustomerSource v-model:value="formState.brly" class="w-full" @change="onChangeSelect" />
              </a-descriptions-item>
            </a-descriptions>
            <a-form-item class="w-full">
              <div v-if="tagsList.length > 0" class="flex flex-wrap">
                <div v-for="item in tagsList" :key="item.id" class="tag-item flex items-center mb-2">
                  <div class="tag-item-label truncate max-w-[160px]">{{ item.labelName }}</div>
                  <div class="tag-item-value truncate max-w-[160px]">{{ item.itemNameString }}</div>
                </div>
                <div>
                  <a-button @click="openTagsModal = true"><FormOutlined /></a-button>
                </div>
              </div>
              <a-button v-else type="primary" ghost :disabled="!userInfo.brId" @click="openTagsModal = true">添加标签</a-button>
            </a-form-item>
          </div>
        </UserCard>
      </div>
      <div class="w-1/2">
        <a-form :model="formState" class="form-style-flex">
          <a-form-item label="手术日期" v-bind="validateInfos.aptmOprDate" class="w-1/2">
            <a-date-picker v-model:value="formState.aptmOprDate" :disabled-date="disabledDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
          </a-form-item>
          <a-form-item label="手术时间" class="w-1/2">
            <a-time-picker v-model:value="formState.aptmOprTime" value-format="HH:mm" format="HH:mm" />
          </a-form-item>
          <a-form-item label="右眼手术" class="w-full">
            <SelectTable
              v-model:value="formState.odmc"
              type="手术收费项目"
              :select-only-one="formState.brId && !formState.isSelectedOd"
              no-page
              auto-mark
              allow-clear
              :search-params="{ brId: formState.brId, bw: '右眼', jklb: '5' }"
              @select="onSelectOd"
            />
          </a-form-item>
          <a-form-item label="左眼手术" class="w-full">
            <!-- <SelectTable v-model:value="formState.osIcd9MC" type="手术" @select="onSelectOperation($event, 'osIcd9')" /> -->

            <SelectTable
              v-model:value="formState.osmc"
              type="手术收费项目"
              :select-only-one="formState.brId && !formState.isSelectedOs"
              no-page
              auto-mark
              allow-clear
              :search-params="{ brId: formState.brId, bw: '左眼', jklb: '5' }"
              @select="onSelectOs"
            />
          </a-form-item>

          <a-form-item label="手术医生" v-bind="validateInfos.ssys" class="w-full">
            <SelectTable v-model:value="formState.ssys" type="医生" custom-input empty-close @select="onSelectEmp" />
          </a-form-item>
          <!-- <a-form-item label="押金用途" class="w-full">
              <a-select
                v-model:value="formState.zzys"
                :options="depositDoctor"
                placeholder="请选择"
                :field-names="{ label: 'pathName', value: 'id' }"
                @focus="getExpressMode"
                @change="onChangexpressMode"
              />
            </a-form-item> -->
          <a-form-item label="备注" class="w-full">
            <a-textarea v-model:value="formState.memo" :rows="5" placeholder="请输入" />
          </a-form-item>
        </a-form>
      </div>
    </div>
    <TagsModal v-model:open="openTagsModal" :tag-data="tagsList" @success="onSelectTags" />
  </a-modal>
</template>
<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { FormOutlined } from '@ant-design/icons-vue'
import { groupBy } from 'lodash-es'
import { post } from '@/utils/request'
import SelectTable from '@/components/SelectTable'
// import LabelValue from '@/components/LabelValue'
import UserCard from '@/components/UserCard'
import TagsModal from '@/components/business/TagsModal'
import cofirmModal from '@/utils/confirm'

const userInfo = ref({})
const emit = defineEmits(['update:open', 'success'])
const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => ({})
  }
})
const openTagsModal = ref(false)
const formState = ref({
  aptmOprDate: '',
  aptmOprTime: '',
  ssys: '',
  aptmOdOprBhName: '',
  aptmOsOprBh: '',
  aptmOsOprBhName: '',
  aptmOdOprBh: '',
  brId: '',
  brName: '',
  brXb: '',
  brAge: ''
})
const interestProject = ref([])
const rulesState = ref({
  aptmOprDate: [{ required: true, message: '请选择手术日期' }],
  ssys: [{ required: true, message: '请选择手术医生' }]
})
const onSelectEmp = (select) => {
  formState.value = {
    ...formState.value,
    aptmOprEmpId: select.empId,
    ssys: select.empName
  }
}

//获取标签
const tagsList = ref([])
const { resetFields, isCompleted, validateInfos } = useForm(formState, rulesState)

const onSelectPatient = async (select) => {
  //选择下拉表
  formState.value = {
    ...formState.value,
    ...select,
    brNames: select.brName
  }
  userInfo.value = {
    ...select
  }
  getTagsList()
}
const onSelectOs = async (select) => {
  formState.value = {
    ...formState.value,
    isSelectedOs: true,
    osmc: select.mc,
    aptmOsOprBh: select?.bh || select?.sfxmbh
  }
}
const onSelectOd = async (select) => {
  formState.value = {
    ...formState.value,
    isSelectedOd: true,
    odmc: select.mc,
    aptmOdOprBh: select?.bh || select?.sfxmbh
  }
}
//获取标签
const getTagsList = async () => {
  const { code, data, msg } = await post('/common/label/getLableListByPatientld', { brId: userInfo.value.brId })
  if (code !== 0) return message.error(msg || '获取标签失败')
  tagsList.value = groupsList(data, 'labelId')
  userInfo.value.labelList = data.map((tag) => tag.itemId)
}
const groupsList = (list) => {
  const groupedByLabelId = groupBy(list, 'labelId')
  const result = []
  for (const labelId in groupedByLabelId) {
    const items = groupedByLabelId[labelId]
    result.push({
      labelId,
      labelName: items[0].labelName,
      itemId: items.map((item) => item.itemId),
      itemName: items.map((item) => item.itemName),
      itemNameString: items.map((item) => item.itemName).join(', ')
    })
  }
  return result
}
const onSelectTags = async (tags = []) => {
  userInfo.value.labelList = tags.map((tag) => tag.id)
  tagsList.value = groupsList(tags)
  const res = await post('/operation/opex/doAddLabelList', { brId: userInfo.value.brId, labelList: userInfo.value.labelList })
  if (res.code !== 0) return message.error(res.msg || '获取数据失败')
}
const getInterestProject = async () => {
  const { data, code, msg } = await post('/operation/opex/getDictFocusItemList', { zjm: '' })
  if (code !== 0) return message.error(msg || '获取数据失败')
  interestProject.value = data.map((item) => {
    return {
      label: item.itemName,
      value: item.id
    }
  })
}
const onChangeSelect = async () => {
  if (formState.value.brName) {
    formState.value.jksy = 0
    const res = await post('/common/patient/savePatientInfo', formState.value)
    if (res.code !== 0) return message.error(res.msg || '失败')
  }
}

const disabledDate = (current) => {
  // 禁用今天之前的日期
  return current && current < new Date(new Date().toDateString())
}
const onOk = async () => {
  if (!formState.value.brName) return message.error('姓名不能为空')
  // if (!formState.value.aptmOsOprBh || !formState.value.aptmOdOprBh) return message.error('必须选择一种手术')
  if (props.rowData?.aptmLsh) {
    onRequest()
  } else {
    getAppointment()
  }
}

const getAppointment = async () => {
  const res = await post('/operation/opex/chekDoAppointment', { brId: formState.value.brId })
  if (res.code !== 0) return message.error(res.msg)
  if (res.data) {
    const isConfirm = await cofirmModal({ title: '提示', content: res.data })
    if (isConfirm) {
      onRequest()
    }
  } else {
    onRequest()
  }
}

const onRequest = async () => {
  const res = await post('/operation/opex/doAppointment', formState.value)
  if (res.code !== 0) return message.error(res.msg)
  message.success(res.msg)
  emit('success')
  onCancel()
}

const onCancel = () => {
  emit('update:open', false)
  resetFields()
}
const getUserInfo = async (brId) => {
  //获取病人信息
  const { code, data, msg } = await post('/outp/mzdj/getPatientInfoList', { brId, pageNum: 1, pageSize: 10 })
  if (code !== 0) return message.error(msg)
  userInfo.value = {
    ...data[0]
  }
}

watch(
  () => props.open,
  (val) => {
    if (val) {
      getInterestProject()
      if (props.rowData?.aptmLsh) {
        formState.value = { ...props.rowData }
        getUserInfo(props.rowData?.brId)
        userInfo.value.brId = props.rowData?.brId
        getTagsList()
      } else {
        userInfo.value = {}
        formState.value = {}
        tagsList.value = []
      }
    }
  }
)
watch(
  () => formState.value.osmc,
  (val) => {
    if (!val) {
      formState.value.aptmOsOprBh = ''
    }
  }
)
watch(
  () => formState.value.odmc,
  (val) => {
    if (!val) {
      formState.value.aptmOdOprBh = ''
    }
  }
)
</script>

<style lang="less" scoped>
.ant-descriptions {
  :deep(.ant-descriptions-item-label) {
    padding-top: 3px;
  }
}
.tag-item {
  margin-right: 8px;
  overflow: hidden;
  border: 1px solid var(--primary-color);
  border-radius: 8px;
  .tag-item-label {
    padding: 4px 12px;
    color: #fff;
    background-color: var(--primary-color);
  }
  .tag-item-value {
    padding: 4px 12px;
  }
}
.ant-tag-checkable-checked {
  color: #fff;
  background-color: var(--primary-color);
}
</style>
